#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器");
    tcpServer = new QTcpServer(this);
    connect(tcpServer, &QTcpServer::listen, this, &Widget::processConnection);
    bool ret = tcpServer->listen(QHostAddress::Any, 9090);
    if(!ret)
    {
        QMessageBox::critical(this, "服务器启动失败", tcpServer->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString log = "[" + clientSocket->peerAddress().toString() + ":" +QString::number(clientSocket->peerPort()) + "] 客户端上线";
    ui->listWidget->addItem(log);
    connect(clientSocket, &QTcpSocket::readyRead, this, [=](){
        QString request = clientSocket->readAll();
        const QString& response = process(request);
        clientSocket->write(response.toUtf8());
        QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "] req: " + request + ", resp: " + response;
        ui->listWidget->addItem(log);
    });
    connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
        QString log = "[" + clientSocket->peerAddress().toString() + ":" +QString::number(clientSocket->peerPort()) + "] 客户端下线";
        ui->listWidget->addItem(log);
        //delete clientSocket;//一定要放在最后，因为这个connect是和其有关的而且前面还需要防止return... --- 下策
        clientSocket->deleteLater();//下一轮事件进行delete！
    });
}
QString Widget::process(const QString& request)
{
    return request;
}
